<template>
  <div class="order-management">
    <!-- 基础搜索 -->

    <!-- 条件搜索 -->
    <el-form inline class="search-form">
      <el-form-item label="用户账号">
        <el-input v-model="searchUserName" placeholder="用户账号"></el-input>
      </el-form-item>
      <el-form-item label="用户地址">
          <el-input v-model="searchAddress" placeholder="用户地址"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">高级搜索</el-button>
        <el-button @click="clearSearch">清空搜索</el-button>
      </el-form-item>
    </el-form>

    <!-- 批量操作按钮 -->
    <div style="text-align: left">
      <el-button type="danger" @click="deleteSelectedOrders" :disabled="selectedOrderIds.length === 0">删除选中订单
      </el-button>
    </div>

    <el-table
        :data="orders"
        style="width: 100%"
        @selection-change="handleSelectionChange"
    >
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column prop="oid" label="订单编号"></el-table-column>
      <el-table-column label="商品" width="120">
        <template slot-scope="scope">
          <el-avatar :size="60" :src="scope.row.flower.fsrc"  @error="errorHandler" shape="square">
            <img src="imgs/avatar_error.png"/>
          </el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="user.username" label="客户名称"></el-table-column>
      <el-table-column prop="flower.fname" label="商品名称"></el-table-column>
      <el-table-column prop="oprice" label="订单价格"></el-table-column>
      <el-table-column prop="quantity" label="数量"></el-table-column>
      <el-table-column prop="address" label="地址"></el-table-column>
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      <el-table-column label="订单状态">
        <template slot-scope="scope">
          <el-button
              v-if="scope.row.state === 1"
              type="info"
              disabled
          >未支付</el-button>
          <el-button
              v-else-if="scope.row.state === 2"
              type="success"
              disabled
          >已支付</el-button>
          <el-button
              v-if="scope.row.state === 3"
              type="info"
              @click="updateStatus(scope.row, 4)"
          >待发货</el-button>
          <el-button
              v-else-if="scope.row.state === 4"
              type="success"
              disabled
          >待收货</el-button>
          <el-button
              v-if="scope.row.state === 5"
              type="success"
              disabled
          >已完成</el-button>
          <el-button
              v-if="scope.row.state === 0"
              type="success"
              @click="isUpdate(scope.row)"
          >退款申请</el-button>
          <el-button
              v-if="scope.row.state === 6"
              type="success"
             disabled
          >已退款</el-button>
          <el-button
              v-if="scope.row.state === 7"
              type="success"
              disabled
          >退款申请拒绝了</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="danger" @click="deleteOrder(scope.row.oid)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNums"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
    >
    </el-pagination>
    <!-- 修改的模态框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form :model="orderss"  ref="sbuinessForm" label-width="120px">
        <el-form-item label="鲜花编码" prop="fid">
          <el-input v-model="orderss.oid" autocomplete="off" readonly></el-input>
        </el-form-item>
        <el-form-item label="鲜花编码" prop="fid">
          <el-input v-model="orderss.fid" autocomplete="off" readonly></el-input>
        </el-form-item>
        <el-select v-model="orderss.state"  placeholder="请选择">
          <el-option
              v-for="item in statess"
              :key="item.tid"
              :label="item.tname"
              :value="item.tid">
          </el-option>
        </el-select>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelSubmit">取 消</el-button>
        <el-button type="primary"  @click="isUpdates">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Table, TableColumn, Input, Button, Pagination, Form, FormItem, Select, Option, Col } from 'element-ui';
import request from "@/utils/request";


export default {
  components: {
    [Table.name]: Table,
    [TableColumn.name]: TableColumn,
    [Input.name]: Input,
    [Button.name]: Button,
    [Pagination.name]: Pagination,
    [Form.name]: Form,
    [FormItem.name]: FormItem,
    [Select.name]: Select,
    [Option.name]: Option,
    [Col.name]: Col
  },
  data() {
    return {
      dialogFormVisible: false,
      Shops: {
        sid: '',
        sname: '',
        spassword: '',
        siphone: '',
        src: ''
      },
      orders: [],
      searchQuery: '',
      minPrice: null,
      maxPrice: null,
      searchUserName: null,
      searchAddress: null,
      currentPage: 1,
      pageNums: 1,
      pageSize: 10,
      total: '',
      selectedOrderIds: [], // 用于存储选中的订单ID
      order: {
        oid : '',
        user: {
          id: '',
          username: '',
          password: '',
          iphone: '',
          src: ''
        },
        shops: {
          sid: '',
          sname: '',
          spassword: '',
          siphone: '',
          src: ''
        },
        flower: {
          fid: '',
          fname: '',
          faddress: '',
          flangure: '',
          fsrc: '',
          price: '',
          number: '',
          types: {
            tid: '',
            tname: '',
            sid: ''
          },
          shops:{
            sid: '',
            sname: '',
            spassword: '',
            siphone: '',
            src: ''
          }
        },
        oprice: '',
        createTime: '',
        state: 1,
        address: '',
        quantity:'',
        appraise: '',
        points: '',
        comment: ''
      },
      orderss:{
        oid : '',
        fid: '',
        state: '',
      },
      statess: [
        {tid: 6,
          tname: '同意退款'
        },
        {tid:7,  tname:'不同意退款'}
      ],
      title: '退款单'
    }
  },
  computed: {
    filteredOrders() {
      let result = this.orders;
      if (this.searchQuery) {
        result = result.filter(order => order.customerName.toLowerCase().includes(this.searchQuery.toLowerCase()));
      }
      if (this.searchUserId) {
        result = result.filter(order => order.id === parseInt(this.searchUserId));
      }
      if (this.minPrice !== null) {
        result = result.filter(order => order.price >= this.minPrice);
      }
      if (this.maxPrice !== null) {
        result = result.filter(order => order.price <= this.maxPrice);
      }
      if (this.searchStatus) {
        result = result.filter(order => order.status === parseInt(this.searchStatus));
      }
      return result;
    },
    pagedOrders() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.filteredOrders.slice(start, end);
    }
  },
  methods: {
    isUpdates(){
      alert(1)
      request({
        url: 'http://localhost:9092/Order/isUpdate',
        method: 'post',
        params:{
          oid: this.orderss.oid,
          fid: this.orderss.fid,
          state: this.orderss.state
        }
      }).then(response => {
        if (response.data.code === 200) {
          this.$message({
            type: 'success',
            message: response.data.msg
          });
         this.getToken()
          this.dialogFormVisible = false;
        } else {
          this.$message({
            type: 'error',
            message: response.data.msg
          });
        }
      }).catch(error => {
        console.error('请求失败:', error);
      });
    },
    cancelSubmit(){
      this.orderss.oid = '';
      this.orderss.fid = '';
      this.dialogFormVisible = false;
    },
    isUpdate(data){
      this.orderss.oid = data.oid;
      this.orderss.fid = data.flower.fid;
      this.dialogFormVisible = true;
    },
    getToken(){
      request({
        method: 'post',
        url: 'http://localhost:9092/shops/getTook',
      }).then(res => {
        if (res.data.code === 200) {
          this.Shops = res.data.data;
          this.getOrder()
        }else {
          this.$router.replace("/")
        }
      })
    },
    getOrder(){
      request({
        url: 'http://localhost:9092/Order/getOrder',
        method: 'post',
      }).then(response => {
        if (response.data.code === 200) {
          console.log(response.data.data)
          this.$message({
            type: 'success',
            message: response.data.msg
          });
          this.orders = response.data.data;
        } else {
          this.$message({
            type: 'error',
            message: response.data.msg
          });
        }
      }).catch(error => {
        console.error('请求失败:', error);
      });
    },
    deleteOrder(orderId) {
        this.order.oid = orderId;
        this.order.shops.sname = this.Shops.sname
      request({
        url: 'http://localhost:9092/Order/deleteOrder',
        method: 'post',
        data: this.order
      }).then(response => {
        if (response.data.code === 200) {
          this.$message({
            type: 'success',
            message: response.data.msg
          });
          this.getToken()
        } else {
          this.$message({
            type: 'error',
            message: response.data.msg
          });
        }
      }).catch(error => {
        console.error('请求失败:', error);
        this.$message.error('请求失败');
      });
    },
    updateStatus(order, newStatus) {
      let ordersss = {
        oid : order.oid,
        state : newStatus,
        shops: {
          sname : order.shops.sname
        }
      };
      request({
        url: 'http://localhost:9092/Order/updateOrder',
        method: 'post',
        data: ordersss
      }).then(response => {
        if (response.data.code === 200) {
          console.log(response.data.data)
          this.$message({
            type: 'success',
            message: response.data.msg
          });
          this.getToken()
        } else {
          this.$message({
            type: 'error',
            message: response.data.msg
          });
        }
      }).catch(error => {
        console.error('请求失败:', error);
        this.$message.error('请求失败');
      });
    },
    handleSearch() {
      // 重置当前页码
      if(this.searchAddress===null && this.searchUserName === null){
        this.$message({
          type: 'error',
          message: '不好意思,请输入条件'
        });
      }else {
        this.currentPage = 1;
        request({
          url: 'http://localhost:9092/Order/findOrder',
          method: 'post',
          params: {
            username: this.searchUserName,
            address: this.searchAddress
          }
        }).then(response => {
          if (response.data.code === 200) {
            this.$message({
              type: 'success',
              message: response.data.msg
            });
            this.orders = response.data.data;
            console.log(this.orders)
          } else {
            this.$message({
              type: 'error',
              message: response.data.msg
            });
          }
        }).catch(error => {
          console.error('请求失败:', error);
          this.$message.error('请求失败');
        });
      }
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
    },
    clearSearch() {
      this.searchQuery = '';
      this.searchUserName= null;
      this.minPrice = null;
      this.maxPrice = null;
      this.searchAddress = null;
      this.currentPage = 1; // 重置到第一页
      this.selectedOrderIds = []; // 清空已选
      this.getToken()
    },
    handleSelectionChange(selection) {
      this.selectedOrderIds=[]
      for (let i = 0; i < selection.length; i++) {
        this.selectedOrderIds.push(selection[i].oid);
      }
      console.log(this.selectedOrderIds)
    },
    deleteSelectedOrders() {
      console.log(this.selectedOrderIds)
      request({
        url: 'http://localhost:9092/Order/deleteMoreOrder',
        method: 'post',
        data: this.selectedOrderIds
      }).then(response => {
        if (response.data.code === 200) {
          console.log(response.data.data)
          this.$message({
            type: 'success',
            message: response.data.msg
          });
          this.getToken()
        } else {
          this.$message({
            type: 'error',
            message: response.data.msg
          });
        }
      }).catch(error => {
        console.error('请求失败:', error);
        this.$message.error('请求失败');
      });
    }
  },
  created() {
    this.getToken();
  }
}
</script>

<style>
.order-management {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.line {
  text-align: center;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}
</style>